package com.demo.io.nio;

import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;

/**
 * 接受消息
 *
 * @author lee9213@163.com
 * @version 1.0
 * @date 2017/3/20 18:01
 */
public class AcceptJob implements Runnable {
    private Selector clientSelector;
    private Selector serverSelector;

    public AcceptJob(Selector clientSelector, Selector serverSelector) {
        this.clientSelector = clientSelector;
        this.serverSelector = serverSelector;
    }

    @Override
    public void run() {
        try {
            while (true) {
                int n = serverSelector.selectNow();
                if (n <= 0) continue;
                Iterator<SelectionKey> iterator = serverSelector.selectedKeys().iterator();
                while (iterator.hasNext()) {
                    SelectionKey selectionKey = iterator.next();
                    if (selectionKey.isAcceptable()) {
                        ServerSocketChannel serverSocketChannel = (ServerSocketChannel) selectionKey.channel();
                        SocketChannel socketChannel = serverSocketChannel.accept();
                        socketChannel.configureBlocking(false);
                        socketChannel.register(clientSelector, SelectionKey.OP_READ);
                    }
                    iterator.remove();
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}
